package com.source.thread;

import java.util.UUID;

public class ProductorAndCOnsumer2 {
    public static void main(String[] args) {
        Data data =new Data();

        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Productor-AA").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Consumer-AA").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Productor-BB").start();



        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Consumer-BB").start();

    }
}


class   Data{

    private  String  task =null;

    public synchronized void produce() throws InterruptedException {
        while(task!=null){   //  为什么不用if 判断。。。。。。。。。。。。。。。。。。。。。。
            this.wait();
        }
        task= UUID.randomUUID().toString().substring(4,8);
        this.notifyAll();
        System.out.println("上产者为"+Thread.currentThread().getName()+"=>生产的内容为："+task);

    }

    public  synchronized  void consumer() throws InterruptedException {

         while(task==null){
             this.wait();
         }
        System.out.println("消费者为"+Thread.currentThread().getName()+"=>"+task);
        task =null;
        this.notifyAll();
    }
}